package com.zh.config;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.EnumSet;

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }

    @Override
    protected String[] getServletMappings() {
        //<!--请求资源全部拦截-->
        return new String[]{"/"};
    }

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        //<!--    配置web启动时通过监听器加载spring运行环境-->tomcat启动时先加载spring配置
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringConfiguration.class);
        return ctx;
    }

    //中文过滤
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        CharacterEncodingFilter cef = new CharacterEncodingFilter();
        cef.setEncoding("UTF-8");
        FilterRegistration.Dynamic reg = servletContext.addFilter("characterEncodingFilter", cef);
        reg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST,DispatcherType.FORWARD,DispatcherType.INCLUDE),false,"/*");
    }
    /**
     *  中文过滤-->
     *     <filter>
     *       <filter-name>characterEncodingFilter</filter-name>
     *       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
     *       <init-param>
     *         <param-name>encoding</param-name>
     *         <param-value>UTF-8</param-value>
     *       </init-param>
     *     </filter>
     *     <filter-mapping>
     *       <filter-name>characterEncodingFilter</filter-name>
     *       <url-pattern>/*</url-pattern>
     *     </filter-mapping>
     */
}
